package com.food.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.food.entity.po.FoodApiGd;
import com.food.entity.po.FoodApiBaidu;
import com.food.entity.po.FoodApiTx;
import com.food.mapping.FoodShopMapper;
import com.food.service.FoodShopService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author : 港某
 * @date : 2021/1/7 14:47
 */
@Slf4j
@Component
public class GenerateData {

    @Resource
    FoodShopService foodShopService;

    @Resource
    FoodShopMapper foodShopMapper;

    /**
     * 通过高德地图api<br>
     * 获取成都饮食餐饮数据<br>
     * 并存入数据库中
     */
    public void generateData() {
        //清除原有数据
        foodShopMapper.deleteFoodShop();
        int count = 0;
        int offset = 10;
        int page = 1;
        do {
            String url = "http://restapi.amap.com/v3/place/text?key=cbe5ed218789ffe1858ed5d6432204a9&keywords=S" +
                    "&types=餐饮服务&city=510100&children=1&offset=" + offset + "&page=" + page + "&extensions=all";
            Connection.Response execute = null;
            try {
                //调用高德地图api
                execute = Jsoup.connect(url)
                        .ignoreContentType(true)
                        .ignoreHttpErrors(true)
                        .method(Connection.Method.GET)
                        .execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (execute != null) {
                String body = execute.body();
                //解析高德地图返回的数据
                JSONObject jsonObject = JSON.parseObject(body);
                JSONArray jsonArray = jsonObject.getJSONArray("pois");
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObj = jsonArray.getJSONObject(i);
                        //生成主键
                        String objId = MyUtil.generateObjId();
                        FoodApiGd foodApiGd = jsonObj.toJavaObject(FoodApiGd.class);
                        //获取详情
                        JSONObject bizExt = jsonObj.getJSONObject("biz_ext");
                        if (bizExt != null) {
                            try {
                                foodApiGd.setRating(bizExt.getDoubleValue("rating"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            try {
                                foodApiGd.setCost(bizExt.getDoubleValue("cost"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        //设置主键
                        foodApiGd.setObjId(objId);
                        foodShopService.insertFoodShop(foodApiGd);
                        //获取餐饮店的图片
                        JSONArray jsonArr = jsonObj.getJSONArray("photos");
                        //插入数据库中
                    }
                    count = jsonArray.size();
                } else {
                    count = 0;
                }
                page++;
            } else {
                count = 0;
            }
        } while (count != 0);
    }

    /**
     * 通过百度地图api<br>
     * 获取成都饮食餐饮数据<br>
     * 并存入数据库中
     */
    public void generateDataBaidu() {
        //清除原有数据
        foodShopMapper.deleteFoodShopBaidu();
        int count = 0;
        int offset = 10;
        int page = 1;
        do {
            String url = "http://api.map.baidu.com/place/v2/search?query=美食&city_limit=true&region=成都市&output=json" +
                    "&ak=txmMQppKzfVGtG22Rm2cSGYGGfFdXYaW&scope=2&page_size=" + offset + "&page_num=" + page;
            Connection.Response execute = null;
            try {
                //调用百度地图api
                execute = Jsoup.connect(url)
                        .ignoreContentType(true)
                        .ignoreHttpErrors(true)
                        .method(Connection.Method.GET)
                        .execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (execute != null) {
                JSONObject jsonObject = JSON.parseObject(execute.body());
                if (jsonObject != null) {
                    JSONArray jsonArray = jsonObject.getJSONArray("results");
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            FoodApiBaidu foodApiBaidu = object.toJavaObject(FoodApiBaidu.class);
                            //设置主键
                            foodApiBaidu.setObjId(UUID.randomUUID().toString());
                            foodApiBaidu.setInsertTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                            //获取详细信息
                            JSONObject detailInfo = object.getJSONObject("detail_info");
                            if (detailInfo != null) {
                                foodApiBaidu.setDetailUrl(detailInfo.getString("detail_url"));
                                foodApiBaidu.setPrice(detailInfo.getDoubleValue("price"));
                                foodApiBaidu.setOverallRating(detailInfo.getDoubleValue("overall_rating"));
                                foodApiBaidu.setCommentNum(detailInfo.getLong("comment_num"));
                                foodApiBaidu.setTag(detailInfo.getString("tag"));
                                foodApiBaidu.setType(detailInfo.getString("type"));
                                //获取精准坐标
                                JSONObject location = detailInfo.getJSONObject("navi_location");
                                if (location != null) {
                                    foodApiBaidu.setLatitude(location.getDoubleValue("lat"));
                                    foodApiBaidu.setLongitude(location.getDoubleValue("lng"));
                                }
                            }
                            foodShopMapper.insertFoodShopBaidu(foodApiBaidu);
                        }
                        count = jsonArray.size();
                    } else {
                        count = 0;
                    }
                } else {
                    count = 0;
                }
                page++;
            } else {
                count = 0;
            }
        } while (count != 0);
    }

    /**
     * 获取腾讯地图api数据
     */
    public void generateDataTx() {
        foodShopMapper.deleteFoodShopTx();
        int pageIndex = 1;
        do {
            String url = "https://apis.map.qq.com/ws/place/v1/search?keyword=%E7%BE%8E%E9%A3%9F&boundary=region(成都,0)" +
                    "&key=QA5BZ-66GWX-GJE4U-7FNK3-DJJWE-JVBG2&page_size=10&page_index=" + pageIndex;
            Connection.Response execute = null;
            try {
                execute = Jsoup.connect(url)
                        .ignoreContentType(true)
                        .ignoreHttpErrors(true)
                        .method(Connection.Method.GET)
                        .execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (execute != null) {
                String body = execute.body();
                JSONArray jsonArray = JSON.parseObject(body).getJSONArray("data");
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        FoodApiTx object = jsonObject.toJavaObject(FoodApiTx.class);
                        System.out.println(object);
                        object.setObjId(UUID.randomUUID().toString());
                        JSONObject location = jsonObject.getJSONObject("location");
                        if (location != null) {
                            object.setLng(location.getDouble("lng"));
                            object.setLat(location.getDouble("lat"));
                        }
                        JSONObject adInfo = jsonObject.getJSONObject("ad_info");
                        if (adInfo != null) {
                            object.setAdcode(adInfo.getString("adcode"));
                            object.setProvince(adInfo.getString("province"));
                            object.setCity(adInfo.getString("city"));
                            object.setDistrict(adInfo.getString("district"));
                        }
                        //存入数据库
                        foodShopMapper.insertFoodShopTx(object);
                    }
                }
            }
            pageIndex++;
        } while (pageIndex < 250);

    }

    public static void main(String[] args) {

    }

}
